import { Injectable } from '@angular/core';
import { DrillFormControl } from '../..';
import { FormGroup } from '@angular/forms';

@Injectable()
export class DrillFormService {
	/**
	 * 根据表单设置信息，初始化成table显示的处理数据结构。
	 * @param formcontrols 表单设置信息
	 */
	getTableFormControls(formcontrols: Array<DrillFormControl>): Array<Array<DrillFormControl>> {
		const reslut = new Array<Array<DrillFormControl>>();
		let maxRowIndex = 0;
		let findmaxRowspan = 0;
		// 找到最大行数
		formcontrols.forEach(e => {
			const maxValue = e.inputRowIndex >= e.labelRowIndex ? e.inputRowIndex : e.labelRowIndex;
			if (maxValue > maxRowIndex) {
				maxRowIndex = maxValue;
				findmaxRowspan = e.labelRowSpan > e.inputRowSpan ? e.labelRowSpan : e.inputRowSpan;
			}
		});
		// 找到所有已经设置了行列的数据。
		for (let i = 1; i <= maxRowIndex + findmaxRowspan; i++) {
			const findResult = formcontrols
				.filter(e => (e.labelRowIndex === i || e.inputRowIndex === i) && e.showInForm)
				.sort(e => e.labelRowIndex);
			if (findResult) {
				reslut.push(findResult.reverse());
			}
		}
		// 没有设置行列的内容，按照独占一行处理。
		// formcontrols
		// 	.filter(e => e.labelRowIndex === 0 || e.labelRowIndex === 0)
		// 	.forEach(e => {
		// 		reslut.push(new Array<DrillFormControl>(e));
		// 	});
		return reslut;
	}

	/**
 * 模型值复制到formgroup
 *
 * @protected
 * @param {FormGroup} fb
 * @param {T} entity
 * @returns {*}
 * @memberof FormViewBaseComponent
 */
	setEntityToFormGroup(fb: FormGroup, entity: any): FormGroup {
		for (const key of Object.keys(entity)) {
			if (fb.controls[key]) {
				fb.controls[key].setValue(entity[key]);
			}
		}
		return fb;
	}

	/**
* 从formgroup中获取值到传输模型
*
* @protected
* @param {FormGroup} fb
* @param {T} entity
* @returns {T}
* @memberof FormViewBaseComponent
*/
	getEntityFromFormGroup(fb: FormGroup, entity: any): any {
		for (const key of Object.keys(fb.controls)) {
			entity[key] = fb.controls[key].value;
		}
		return entity;
	}
}
